/*
 *  Copyright (C) 2011 glauco
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.balisunrise.samples;

import java.util.logging.Level;
import org.balisunrise.annotation.Action;
import org.balisunrise.annotation.ActionMap;
import org.balisunrise.annotation.EventType;
import org.balisunrise.annotation.FilterType;
import org.balisunrise.application.Application;
import org.balisunrise.builder.CommonFactory;
import org.balisunrise.builder.FactoryException;
import org.balisunrise.common.Criterion;
import org.balisunrise.common.events.BeforeLoadEvent;
import org.balisunrise.common.events.BeforeSaveEvent;

/**
 * Mapa de ações do cliente
 * @author Glauco
 */
@ActionMap(classes=Cliente.class)
public class ClienteActions {

    private static final Application app;
    private static final CommonFactory factory;

    static {
        app = Application.get();
        factory = app.getFactory();
    }

    @Action(target=EventType.ENTITY_FILTER_BEFORE_LOAD,alias="def")
    public void filtroPessoaFisica(BeforeLoadEvent evt){
        try{
            Criterion c = factory.createBaliCriterion(Cliente.PROP_TIPOPESSOA);
            c.setFilterType(FilterType.EQUALS);
            c.setValue(TipoPessoa.FISICA);
            c.setEmptyForAll(true);
            evt.getQuery().addCriterion(c);
        }catch(FactoryException ex){
            app.getLogger().log(Level.WARNING, "Filtro Pessoa Fisica", ex);
        }
    }

    @Action(target=EventType.ENTITY_FILTER_BEFORE_LOAD,alias="jur")
    public void filtroPessoaJuridica(BeforeLoadEvent evt){
        try{
            Criterion c = factory.createBaliCriterion(Cliente.PROP_TIPOPESSOA);
            c.setFilterType(FilterType.EQUALS);
            c.setValue(TipoPessoa.JURIDICA);
            c.setEmptyForAll(true);
            evt.getQuery().addCriterion(c);
        }catch(FactoryException ex){
            app.getLogger().log(Level.WARNING, "Filtro Pessoa Juridica", ex);
        }
    }

    @Action(target=EventType.TRANSACTION_BEFORE_SAVE)
    public void beforeSave(BeforeSaveEvent evt){
        Object entity = evt.getTransaction().getEditor().getEntity();
        if (entity instanceof Cliente)
            ((Cliente) entity).atualizaDataAlteracao();
    }
}
